module site {
    /**
     * 单张地图的使用
     */
    export class SingletonSiteManager implements ISiteInternal, ISitePublic {
        private _mapUnitData: MapUnitData;

        constructor() {
            this._mapUnitData = new MapUnitData();
        }

        /**
         * 
         * @param siteUnitData 
         */
        enter(siteUnitData: ISiteUnitData): void {
            let old = this._mapUnitData.locations[siteUnitData.roleId];
            this._mapUnitData.locations[siteUnitData.roleId] = siteUnitData;

            // 位置有变化才进行广播
            if (old && site.siteEquals(old, siteUnitData)) {
                return;
            }

            this._broadcast(siteUnitData.roleId, 'enter');
        }

        /**
         * 
         * @param roleId 
         */
        exit(roleId: number): void {
            let unitData = this._mapUnitData.locations[roleId];
            if (!unitData) {
                return;
            }

            delete this._mapUnitData.locations[roleId];

            this._broadcast(roleId, 'exit');
        }

        /**
         * 
         * @param data 
         */
        updateLocation(data: ISiteUnitData): void {
            let _locations = this._mapUnitData.locations;

            let old = _locations[data.roleId];
            if (site.siteEquals(data, old)) {
                return;
            }

            _locations[data.roleId] = data;
            this._broadcast(data.roleId, 'update', old);
        }

        /**
         * 
         * @param roleId 
         * @param action 
         * @param old 
         */
        private _broadcast(roleId: number, action: 'enter' | 'exit' | 'update', old?: ISiteUnitData): void {
            let _locations = this._mapUnitData.locations;
            for (let otherRoleIdStr in _locations) {
                let otherRoleId = Number(otherRoleIdStr);
                switch (action) {
                    case 'enter':
                        console.log(`roleId:${otherRoleId} receive enter roleId${roleId}`);
                        break;
                    case 'exit':
                        console.log(`roleId:${otherRoleId} receive exit roleId${roleId}`);
                        break;
                    case 'update':
                        console.log(`roleId:${otherRoleId} receive update roleId${roleId} old ${old} new ${this._mapUnitData.locations[roleId]}`)
                        break;
                }
            }


        }

    }
}